package CanvaWeb.CanvaWeb.Service;

import CanvaWeb.CanvaWeb.Repository.ChatMessageRepository;
import CanvaWeb.CanvaWeb.pojo.ChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChatMessageService {

    @Autowired
    private ChatMessageRepository chatMessageRepository;

    // 发送消息
    public ChatMessage sendMessage(Long roomId, Long userId, String message) {
        // 创建并设置 ChatMessage 实体
        ChatMessage messageEntity = new ChatMessage();
        messageEntity.setRoomId(roomId);
        messageEntity.setUserId(userId);
        messageEntity.setMessage(message); // 设置消息内容

        // 保存并返回
        return chatMessageRepository.save(messageEntity);
    }

    // 获取消息列表（分页）
    public List<ChatMessage> getMessages(Long roomId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return chatMessageRepository.findByRoomId(roomId, pageable).getContent();
    }
}


